'''数据转发器'''

'''从服务器接受数据'''

from fastapi import FastAPI
from paho.mqtt import client as mqtt_client
from paho.mqtt import client as s
import uuid
import uvicorn
from pubsub import pub


generated_uuid = uuid.uuid4()

broker = '121.196.236.225'
port = 12010
topic = "python/mqtt"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-'
username = 'admin'
password = 'Admin,123456'


class Transponder():

    '''客户端'''
 
    def on_connect(self, client, userdata, flags, rc,properties):
        pub.sendMessage('transponder/connect',arg=1)
        self.client.subscribe("yyyyy")
    def on_message(client, userdata, msg):
        print(f"{msg.topic} -> {msg.payload.decode()}")
       
    def __init__(self):
         self.client = mqtt_client.Client(client_id=client_id, callback_api_version=mqtt_client.CallbackAPIVersion.VERSION2)
         self.client.username_pw_set(username, password)
         self.client.on_connect = self.on_connect
         self.client.on_message = self.on_message
         ##self.client.message_callback
         print('__init__')

    def connect(self):
        print('begin connect')
        rs=self.client.connect_async(host=broker,port=port)
        print("r-----------------s:"+str(rs))
        self.client.loop_start()
        print('end sssssssssssssss')
    def publish(self, topic,msg):
        print(self.client.is_connected())
        self.client.loop_start()
        result = self.client.publish(topic, msg)
        self.client.loop_stop()
        # result: [0, 1]
        status = result[0]
        print (result)
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")


 